package com.yc.spring.bank.dao;

import com.yc.spring.bank.bean.Account;
import com.yc.spring.bank.bean.Record;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class RecordDaoImpl implements RecordDao{

    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public void insert(Record t) {
        String sql = "insert into bank_oprecord values(default,?,?,null,now(),null)";
        jdbcTemplate.update(sql, t.getAccountId(),t.getMoney());

    }

    @Override
    public List<Record> selectByAccountId(Integer id) {
        String sql = "select * from bank_oprecord where aid=?";
//        List<Record> list = jdbcTemplate.query(sql, new RowMapper<Record>() {
//            @Override
//            public Record mapRow(ResultSet resultSet, int i) throws SQLException {
//                Record ret = new Record();
//                ret.setId(resultSet.getInt("id"));
//                ret.setAccountId(resultSet.getInt("aid"));
//                ret.setMoney(resultSet.getDouble("opmoney"));
//                return ret;
//            }
//        }, id);
        // 匿名类简化为 lambda 表达式
        List<Record> list = jdbcTemplate.query(sql, (resultSet, i)-> {
            Record ret = new Record();
            ret.setId(resultSet.getInt("id"));
            ret.setAccountId(resultSet.getInt("aid"));
            ret.setMoney(resultSet.getDouble("opmoney"));
            return ret;
        }, id);
        return list;
    }
}
